package org.tobuy.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.tobuy.dao.IUserDAO;
import org.tobuy.vo.User;

public class UserDAOImpl implements IUserDAO{
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	ResultSet rs = null;
	public UserDAOImpl(Connection conn){
		this.conn = conn;
	}
	public boolean findLogin(User user) throws Exception{
		boolean flag = false;
		String sql = "SELECT username FROM user WHERE userid=? AND userpass=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, user.getUser_id());
		this.pstmt.setString(2, user.getUser_pass());
		rs = this.pstmt.executeQuery();
		if(rs.next()){
			user.setUser_name(rs.getString(1));
			flag = true;
		}
		this.pstmt.close();
		return flag;
	}
	public User findUser(String id) throws Exception {
		User user = new User();
		String sql = "SELECT * FROM user WHERE userid=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, id);
		rs = this.pstmt.executeQuery();
		if(rs.next()){
			user = getUserFromRs(rs);
		}
		this.pstmt.close();
		return user;
	}
	public List<User> findUser() throws Exception {
		List<User> users = new ArrayList<User>();
		
		String sql ="SELECT * From user";
		this.pstmt = this.conn.prepareStatement(sql);
		rs = this.pstmt.executeQuery();
		while(rs.next()){
			User user = getUserFromRs(rs);
			users.add(user);
		}
		this.pstmt.close();
		return users;
	}
	public boolean addUser(User user) throws Exception {
		boolean flag = false;
		String sql = "INSERT INTO user(userid,username,userpass,address) VALUES(?,?,?,?)";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, user.getUser_id());
		this.pstmt.setString(2, user.getUser_name());
		this.pstmt.setString(3, user.getUser_pass());
		this.pstmt.setString(4, user.getAddress());
		if(pstmt.executeUpdate()!=0){
			flag = true;
		}
		this.pstmt.close();
		return flag;
	}
	public boolean deleteUser(User user) throws Exception {
		boolean flag = false;
		String sql = "DELETE FROM user where userid=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, user.getUser_id());
		if(pstmt.executeUpdate()!=0){
			flag = true;
		}
		this.pstmt.close();
		return flag;
	}
	private User getUserFromRs(ResultSet rs){
		User user = new User();
		try{
			user.setUser_id(rs.getString("userid"));
			user.setUser_name(rs.getString("username"));
			user.setUser_pass(rs.getString("userpass"));
			user.setAddress(rs.getString("address"));
		}catch(SQLException e){
			e.printStackTrace();
		}
		return user;
	}
	
	
}
